import {Action, getModule, Module, Mutation, VuexModule} from "vuex-module-decorators";
import store from "@/store";
import {IUser} from "@/store/pojo/IUser";

@Module({
    name: 'user',
    namespaced: true,
    dynamic: true,
    store,
})
export default class UserStore extends VuexModule {
    public user: IUser = {
        email: "",
        id: 0,
        password: "",
        phone: "",
        position: "",
        username: ""
    };

    /**
     * 从 store 中去取出数据
     */
    get userInfo(): IUser {
        return this.user;
    }

    /**
     * 从 sessionStorage 中取出user的数据，并保存到 store 中。
     */
    get userInfoFromSessionStorage(): IUser {
        if (sessionStorage.getItem("user.username") != null) {
            // @ts-ignore
            this.user.username = sessionStorage.getItem("user.username");

        }
        if (sessionStorage.getItem("user.id") != null) {
            // @ts-ignore
            this.user.id = parseInt(sessionStorage.getItem("user.id"));
        }
        if (sessionStorage.getItem("user.email") != null) {
            // @ts-ignore
            this.user.email = sessionStorage.getItem("user.email");
        }
        if (sessionStorage.getItem("user.password") != null) {
            // @ts-ignore
            this.user.password = sessionStorage.getItem("user.password");
        }
        if (sessionStorage.getItem("user.phone") != null) {
            // @ts-ignore
            this.user.phone = sessionStorage.getItem("user.phone");
        }
        if (sessionStorage.getItem("user.position") != null) {
            // @ts-ignore
            this.user.position = sessionStorage.getItem("user.position");

        }


        return this.user;
    }

    get userId(): number {
        return this.user.id;
    }

    get username(): string {
        return this.user.username;
    }

    /**
     * 保存到 store中
     * @param user
     */
    @Mutation
    setUserInfo(user: IUser): void {
        this.user = user;
    }

    /**
     * 保存数据到sessionStorage中
     * @param userInfo
     */
    @Mutation
    setUserInfoToSessionStorage(userInfo: IUser): void {
        sessionStorage.setItem("user.id", userInfo.id.toString());
        sessionStorage.setItem("user.email", userInfo.email.toString());
        sessionStorage.setItem("user.password", userInfo.password.toString());
        sessionStorage.setItem("user.phone", userInfo.phone.toString());
        sessionStorage.setItem("user.position", userInfo.position.toString());
        sessionStorage.setItem("user.username", userInfo.username.toString());
    }


}

export const UserStoreModule = getModule(UserStore);